package com.szbmyoubao.app.ui.scan

import android.content.Context
import android.content.Intent
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.ellecity06.common.ktx.requestCameraPermission
import com.ellecity06.debugtools.DebugTools.Companion.context

/**
 * @author ellecity06
 * @time 2025/4/2 14:26
 * @des
 */
/**
 * 开启扫码
 */
fun Context.startScan(onScanDelegate: ((String) -> Unit)?) {
    ScanDelegate.instance.addScanResultDelegate(onScanDelegate)
    startActivity(Intent(context, ScanActivity::class.java))
}

fun Fragment.startScan(onScanDelegate: ((String) -> Unit)?) {
    requireActivity().requestCameraPermission {
        ScanDelegate.instance.addScanResultDelegate(onScanDelegate)
        startActivity(Intent(context, ScanActivity::class.java))
    }
}

fun FragmentActivity.startScan(onScanDelegate: ((String) -> Unit)?) {
    requestCameraPermission {
        ScanDelegate.instance.addScanResultDelegate(onScanDelegate)
        startActivity(Intent(context, ScanActivity::class.java))
    }
}

/**
 * @author zavier
 * @time 2025/4/2 14:31
 * @des 扫码代理
 */
class ScanDelegate private constructor() {

    private var scanDelegate: ((String) -> Unit)? = null
        get() {
            return field

        }

    private object Holder {
        val instance = ScanDelegate()
    }

    fun addScanResultDelegate(onScanDelegate: ((String) -> Unit)?) {
        scanDelegate = onScanDelegate
    }

    fun getScanResultDelegate(): ((String) -> Unit)? {
        return scanDelegate
    }

    fun removeScanResultDelegate() {
        addScanResultDelegate(null)
    }


    companion object {
        val instance: ScanDelegate
            get() = Holder.instance
    }
}